package com.suixun.service.impl;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.suixun.dao.LogonlinepayMapper;
import com.suixun.dao.report.ReportActiveDao;
import com.suixun.entity.CustomReport;
import com.suixun.entity.Logonlinepay;
import com.suixun.entity.LogonlinepayExample;
import com.suixun.entity.RptActiveInfo;
import com.suixun.entity.form.ReportActiveForm;
import com.suixun.entity.page.PageModel;
import com.suixun.service.DeviceService;
import com.suixun.service.ReportService;
import com.suixun.util.DateUtil;
import com.suixun.util.StringUtil;
import com.suixun.util.enums.Payment;
import com.suixun.vo.CustomReportVO;

import rop.utils.spring.CollectionUtils;

@Service("reportService")
public class ReportServiceImpl extends BaseServiceImpl implements ReportService{

	@Resource
	private ReportActiveDao reportActiveDao;
	@Resource
	private DeviceService deviceService; 
	@Resource
	private LogonlinepayMapper logonlinepayMapper;
	
	/**
	 * <p>Title: addReport</p>
	 * <p> 功能描述:新增自定义报表 </p>
	 * @param reportForm
	 * @return
	 * @throws ParseException 
	 */
	@Override
	@Transactional
	public int addReport(ReportActiveForm reportForm) {
		Map<String,Object> map = new HashMap<>();
		map.put("reportname", reportForm.getName());
		map.put("createid", reportForm.getUserid());
		map.put("devicetype", reportForm.getDevtype() == null ? null : Integer.parseInt(reportForm.getDevtype()));
		map.put("schoolname", reportForm.getSchool());
		map.put("starttime",reportForm.getSdate());
		map.put("endtime", reportForm.getEdate());
		map.put("teachertel", reportForm.getTeacher());
		map.put("devicestatus", reportForm.getStatus());
		map.put("createname",reportForm.getUsername());
		map.put("province", reportForm.getProvince());
		map.put("city", reportForm.getCity());
		map.put("town", reportForm.getTown());
		if(null == reportForm.getReporttype()) {
			map.put("reporttype", 1);
		}else {
			map.put("reporttype", reportForm.getReporttype());
			map.put("orderstatus", reportForm.getOrderstatus() == null ? null :Integer.parseInt(reportForm.getOrderstatus()));
		}
		return reportActiveDao.addReport(map);
	}
	/**
	 * <p>Title: deleteReport</p>
	 * <p> 功能描述:删除指定自定义报表 </p>
	 * @param reportForm
	 * @return
	 */
	@Override
	@Transactional
	public int deleteReport(ReportActiveForm reportForm) {
		CustomReport customReport = reportActiveDao.queryReport(Integer.parseInt(reportForm.getReportid()));
		if(reportForm.getUserid() == customReport.getCreateid()) {
			return reportActiveDao.deleteReport(Integer.parseInt(reportForm.getReportid()));
		}
		return -1;
	}
	/**
	 * <p>Title: queryCustomReportByPaging</p>
	 * <p> 功能描述:分页查询自定义报表列表 </p>
	 * @param reportForm
	 * @return
	 */
	@Override
	public PageModel<CustomReportVO> queryCustomReportByPaging(ReportActiveForm reportForm) {
		PageModel<CustomReportVO> pageModel = new PageModel<CustomReportVO>();
		pageModel.getQueryparam().put("createid", reportForm.getUserid());
		if (reportForm.getPagecount() != null) {
			pageModel.setPagesize(Integer.parseInt(reportForm.getPagecount()));
		}
		Integer totleRows = reportActiveDao.countCustomReportRows(pageModel);
		pageModel.setTotlepage(totleRows);
		if(StringUtil.isNotEmpty(reportForm.getPagenumber())) {
			pageModel.setCurrentpage(Integer.parseInt(reportForm.getPagenumber()));
		}
		List<CustomReport> customReportList = reportActiveDao.queryCustomReportByPaging(pageModel);
		if(customReportList.size() == 0) {
			pageModel.setQueryresult(null);
			return pageModel;
		}
		List<CustomReportVO> customReportVOs = new LinkedList<>();
		for(CustomReport customReport:customReportList) {
			CustomReportVO customReportVO = new CustomReportVO();
			customReportVO.setCreatename(customReport.getCreatename());
			customReportVO.setCreatetime(DateUtil.formatDateToString(customReport.getCreatetime(), null));
			customReportVO.setReportid(String.valueOf(customReport.getReportid()));
			customReportVO.setReportname(customReport.getReportname());
			customReportVO.setOrderstatus(String.valueOf(customReport.getOrderstatus()));
			customReportVO.setReporttype(String.valueOf(customReport.getReporttype()));
			customReportVOs.add(customReportVO);
			customReportVO = null;
		}
		pageModel.setQueryresult(customReportVOs);
		return pageModel;
	}
	
	/**
	 * 获取续费账单
	 */
	@Override
	public List<RptActiveInfo> getRenewalIncomes(ReportActiveForm reportForm) {
		Map<String,Object> map = new HashMap<>();
		map.put("starttime", reportForm.getStarttime());
		map.put("endtime", reportForm.getEndtime());
		if (Payment.YIJI.equals(reportForm.getPayment())) {
			map.put("reportType", "yiji");
		}else if (Payment.WECHAT.equals(reportForm.getPayment())) {
			map.put("reportType", "wechat");
		}
		List<RptActiveInfo> renewalIncomesList = reportActiveDao.getRenewalIncomes(map);
		//筛选出首次续费
		if(!CollectionUtils.isEmpty(renewalIncomesList)) {
			List<RptActiveInfo> firstIncomesList = null;
			for (RptActiveInfo activeInfo : renewalIncomesList) {
				map = new HashMap<>();
				map.put("addtime", activeInfo.getAddtime());
				map.put("deviceid", activeInfo.getDeviceid());
				firstIncomesList = reportActiveDao.checkFirstRenewal(map);
				//查不到数据，则证明该行数据是首次续费
				if(CollectionUtils.isEmpty(firstIncomesList)) {
					activeInfo.setFirstRenewal(true);
				}
			}
		}
		return renewalIncomesList;
	}
	/**
	 * 获取购买账单
	 */
	@Override
	public List<RptActiveInfo> getPurchaseIncomes(ReportActiveForm reportForm) {
		Map<String,Object> map = new HashMap<>();
		map.put("starttime", reportForm.getStarttime());
		map.put("endtime", reportForm.getEndtime());
		if (Payment.YIJI.equals(reportForm.getPayment())) {
			map.put("reportType", "yiji");
		}else if (Payment.WECHAT.equals(reportForm.getPayment())) {
			map.put("reportType", "wechat");
		}
		List<RptActiveInfo> purchaseIncomesList = reportActiveDao.getPurchaseIncomes(map);
		return purchaseIncomesList;
	}
	/**
	 * 获取易极付退款账单
	 */
	@Override
	public List<RptActiveInfo> getRefundIncomesByYiji(ReportActiveForm reportForm) {
		Map<String,Object> map = new HashMap<>();
		map.put("starttime", reportForm.getStarttime());
		map.put("endtime", reportForm.getEndtime());
		List<RptActiveInfo> refundIncomesList = reportActiveDao.getRefundIncomesByYiji(map);
		return refundIncomesList;
	}
	/**
	 * <p>Title: getDiscountIncomesByWechat</p>
	 * <p> 功能描述:获取限时优惠账单 </p>
	 * @param reportForm
	 * @return
	 */
	@Override
	public List<RptActiveInfo> getDiscountIncomesByWechat(ReportActiveForm reportForm) {
		Map<String,Object> map = new HashMap<>();
		map.put("starttime", reportForm.getStarttime());
		map.put("endtime", reportForm.getEndtime());
		List<RptActiveInfo> discountIncomesList = reportActiveDao.getDiscountIncomesByWechat(map);
		return discountIncomesList;
	}
	/**
	 * <p>Title: exportYijiReport</p>
	 * <p> 功能描述:导出易极付财务报表 </p>
	 * @param reportForm
	 * @return
	 * @throws Exception
	 */
	@Override
	public HSSFWorkbook exportYijiReport(ReportActiveForm reportForm) throws Exception {
		ArrayList<String> listParm = new ArrayList<String>();
		listParm.add("学校名称");
		listParm.add("家长姓名");
		listParm.add("家长电话");
		listParm.add("串号");
		listParm.add("学生号码");
		listParm.add("续费日期");
		listParm.add("有效期");
		listParm.add("续费金额");
		listParm.add("商户订单号");
		listParm.add("成功标记");
		listParm.add("退款原订单号");
		List<List<String>> listValue = new LinkedList<List<String>>();
		List<String> value = null;
		
		List<RptActiveInfo> purchaseIncomesList = getPurchaseIncomes(reportForm);
		List<RptActiveInfo> renewalIncomesList = getRenewalIncomes(reportForm);
		List<RptActiveInfo> refundIncomesList = getRefundIncomesByYiji(reportForm);
		
		if (purchaseIncomesList != null && purchaseIncomesList.size() > 0) {
			for (RptActiveInfo activeInfo : purchaseIncomesList) {
				value = new LinkedList<>();
				listValue.add(getValues(value, activeInfo, Payment.YIJI));
			}
		}
		if (renewalIncomesList != null && renewalIncomesList.size() > 0) {
			for (RptActiveInfo activeInfo : renewalIncomesList) {
				value = new LinkedList<>();
				activeInfo.setIsRenewal(true);
				listValue.add(getValues(value, activeInfo, Payment.YIJI));
			}
		}
		if (refundIncomesList != null && refundIncomesList.size() > 0) {
			for (RptActiveInfo activeInfo : refundIncomesList) {
				value = new LinkedList<>();
				value = getValues(value, activeInfo, Payment.YIJI);
				value.add(getOldOrderNoByRefund(activeInfo.getOrderno()));
				listValue.add(value);
			}
		}
		return exportList("易极付财务报表",listParm,listValue);
	}
	/**
	 * <p>Title: exportWeichatReport</p>
	 * <p> 功能描述:导出微信财务报表 </p>
	 * @param reportForm
	 * @return
	 * @throws Exception
	 */
	@Override
	public HSSFWorkbook exportWeichatReport(ReportActiveForm reportForm) throws Exception {
		ArrayList<String> listParm = new ArrayList<String>();
		listParm.add("学校名称");
		listParm.add("家长姓名");
		listParm.add("家长电话");
		listParm.add("串号");
		listParm.add("学生姓名");
		listParm.add("学生号码");
		listParm.add("续费日期");
		listParm.add("有效期");
		listParm.add("续费金额");
		listParm.add("商户订单号");
		listParm.add("成功标记");
		List<List<String>> listValue = new LinkedList<List<String>>();
		List<String> value = null;
		
		List<RptActiveInfo> purchaseIncomesList = getPurchaseIncomes(reportForm);
		List<RptActiveInfo> renewalIncomesList = getRenewalIncomes(reportForm);
		List<RptActiveInfo> discountIncomesList = getDiscountIncomesByWechat(reportForm);
		if (purchaseIncomesList != null && purchaseIncomesList.size() > 0) {
			for (RptActiveInfo activeInfo : purchaseIncomesList) {
				value = new LinkedList<>();
				listValue.add(getValues(value, activeInfo, Payment.WECHAT));
			}
		}
		if (renewalIncomesList != null && renewalIncomesList.size() > 0) {
			for (RptActiveInfo activeInfo : renewalIncomesList) {
				value = new LinkedList<>();
				activeInfo.setIsRenewal(true);
				listValue.add(getValues(value, activeInfo, Payment.WECHAT));
			}
		}
		if (discountIncomesList != null && discountIncomesList.size() > 0) {
			for (RptActiveInfo activeInfo : discountIncomesList) {
				value = new LinkedList<>();
				listValue.add(getValues(value, activeInfo, Payment.WECHAT));
			}
		}
		return exportList("微信财务报表",listParm,listValue);
	}
	
	/**
	 * <p>Title: getOldOrderNoByRefund</p>
	 * <p> 功能描述:获取退款订单对应的购买订单号 </p>
	 * @param refundOrderNo
	 * @return
	 */
	private String getOldOrderNoByRefund(String refundOrderNo) {
		if (refundOrderNo == null) {
			return null;
		}
		LogonlinepayExample logonlinepayExample = new LogonlinepayExample();
		logonlinepayExample.createCriteria().andOrdernoEqualTo(refundOrderNo);
		List<Logonlinepay> logOnlinepayList = logonlinepayMapper.selectByExample(logonlinepayExample);
		if (logOnlinepayList == null || logOnlinepayList.size() == 0) {
			return null;
		}
		String contractNo = logOnlinepayList.get(0).getContractno();
		if (contractNo == null) {
			return null;
		}
		logonlinepayExample = new LogonlinepayExample();
		logonlinepayExample.createCriteria().andContractnoEqualTo(contractNo);
		logOnlinepayList = logonlinepayMapper.selectByExample(logonlinepayExample);
		if (logOnlinepayList == null || logOnlinepayList.size() == 0) {
			return null;
		}
		String orderNo = null;
		for (Logonlinepay logOnlinepay : logOnlinepayList) {
			if (!"refund".equals(logOnlinepay.getService())) {
				orderNo = logOnlinepay.getOrderno();
				break;
			}
		}
		return orderNo;
	}
	
	private List<String> getValues(List<String> value, RptActiveInfo activeInfo, Payment payment) {
		if (value == null || activeInfo == null) {
			return null;
		}
		value.add(activeInfo.getSchoolname());
		value.add(activeInfo.getPeoplename());
		value.add(activeInfo.getPeopletel());
		value.add(activeInfo.getMdtid());
		if (Payment.WECHAT.equals(payment)) {
			value.add(activeInfo.getStudentname());
		}
		value.add(activeInfo.getSimid());
		value.add(DateUtil.formatDateToString(activeInfo.getAddtime(), null));
		value.add(DateUtil.formatDateToString(activeInfo.getEndtime(), null));
		value.add(activeInfo.getIncome() == null ? null : activeInfo.getIncome().toString());
		value.add(activeInfo.getOrderno());
		value.add(activeInfo.getPayStatus());
		if(activeInfo.getFirstRenewal()) {
			value.add("首次缴费");
		}else if(activeInfo.getIsRenewal()) {
			value.add("续费");
		}
		return value;
	}
	
}
